# 退费审核管理系统 - 一键部署脚本
# 使用方法：以管理员身份运行 .\deploy-refundtask.ps1

# 设置控制台编码
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8

# 配置参数
$DomainName = "localhost"  # 可修改为实际域名
$Port = 8089              # 可修改为其他端口
$AccessPath = "/refundtask/"  # 访问路径
$BackendUrl = "https://www.lzetyy.com:6724"  # 后端API地址
$NginxPath = "C:\nginx"   # Nginx安装路径，可修改

Write-Host "========================================" -ForegroundColor Cyan
Write-Host "    退费审核管理系统 - 一键部署脚本" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""
Write-Host "当前部署配置：" -ForegroundColor Yellow
Write-Host "域名: $DomainName" -ForegroundColor White
Write-Host "端口: $Port" -ForegroundColor White
Write-Host "访问路径: $AccessPath" -ForegroundColor White
Write-Host "后端API: $BackendUrl" -ForegroundColor White
Write-Host "Nginx路径: $NginxPath" -ForegroundColor White
Write-Host ""

# 函数：显示步骤
function Write-Step {
    param([string]$StepNumber, [string]$Description)
    Write-Host "[$StepNumber] $Description..." -ForegroundColor Yellow
}

# 函数：显示成功信息
function Write-Success {
    param([string]$Message)
    Write-Host "✅ $Message" -ForegroundColor Green
}

# 函数：显示错误信息
function Write-Error-Custom {
    param([string]$Message)
    Write-Host "❌ 错误：$Message" -ForegroundColor Red
}

# 函数：显示警告信息
function Write-Warning-Custom {
    param([string]$Message)
    Write-Host "⚠️  警告：$Message" -ForegroundColor Yellow
}

try {
    # 检查管理员权限
    if (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
        Write-Error-Custom "需要管理员权限运行此脚本"
        Write-Host "请右键选择'以管理员身份运行'" -ForegroundColor Yellow
        Read-Host "按任意键退出"
        exit 1
    }

    # 步骤1：检查项目构建
    Write-Step "1/6" "检查项目构建状态"
    if (-not (Test-Path "dist")) {
        Write-Warning-Custom "dist目录不存在，开始构建项目"
        
        # 检查Node.js
        try {
            $nodeVersion = node --version 2>$null
            if (-not $nodeVersion) { throw "Node.js未安装" }
        } catch {
            Write-Error-Custom "未找到Node.js，请先安装Node.js"
            Write-Host "下载地址：https://nodejs.org/" -ForegroundColor Blue
            Read-Host "按任意键退出"
            exit 1
        }
        
        # 安装依赖并构建
        if (-not (Test-Path "node_modules")) {
            Write-Host "正在安装依赖..." -ForegroundColor Blue
            npm install
            if ($LASTEXITCODE -ne 0) {
                Write-Error-Custom "依赖安装失败"
                Read-Host "按任意键退出"
                exit 1
            }
        }
        
        Write-Host "正在构建项目..." -ForegroundColor Blue
        npm run build
        if ($LASTEXITCODE -ne 0) {
            Write-Error-Custom "项目构建失败"
            Read-Host "按任意键退出"
            exit 1
        }
    }
    
    if (-not (Test-Path "dist\index.html")) {
        Write-Error-Custom "构建文件不完整，请检查构建过程"
        Read-Host "按任意键退出"
        exit 1
    }
    
    Write-Success "项目构建检查通过"
    Write-Host ""

    # 步骤2：检查Nginx
    Write-Step "2/6" "检查Nginx安装"
    if (-not (Test-Path "$NginxPath\nginx.exe")) {
        Write-Warning-Custom "未找到Nginx，请先安装"
        Write-Host "下载地址：http://nginx.org/en/download.html" -ForegroundColor Blue
        Write-Host "建议解压到：$NginxPath" -ForegroundColor Blue
        
        $installNginx = Read-Host "是否已安装Nginx到其他位置？(Y/N)"
        if ($installNginx -eq "Y" -or $installNginx -eq "y") {
            $NginxPath = Read-Host "请输入Nginx安装路径"
            if (-not (Test-Path "$NginxPath\nginx.exe")) {
                Write-Error-Custom "指定路径下未找到nginx.exe"
                Read-Host "按任意键退出"
                exit 1
            }
        } else {
            Read-Host "请先安装Nginx后再运行此脚本，按任意键退出"
            exit 1
        }
    }
    Write-Success "Nginx安装检查通过"
    Write-Host ""

    # 步骤3：生成Nginx配置
    Write-Step "3/6" "生成Nginx配置文件"
    $currentPath = Get-Location
    $distPath = Join-Path $currentPath "dist"
    $distPathForNginx = $distPath -replace "\\", "/"
    
    $nginxConfig = @"
worker_processes auto;
error_log logs/error.log;
events {
    worker_connections 1024;
    use select;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    
    # Gzip压缩配置
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_types text/plain text/css text/xml text/javascript application/javascript application/xml+rss application/json;
    
    server {
        listen $Port;
        server_name $DomainName;
        
        # 网站根目录
        root $distPathForNginx;
        index index.html;
        
        # 字符编码
        charset utf-8;
        
        # 访问日志
        access_log logs/access.log;
        
        # 支持Vue Router的history模式
        location $AccessPath {
            try_files `$uri `$uri/ ${AccessPath}index.html;
        }
        
        # API代理到后端服务
        location ${AccessPath}api/ {
            proxy_pass $BackendUrl/api/;
            proxy_set_header Host `$host;
            proxy_set_header X-Real-IP `$remote_addr;
            proxy_set_header X-Forwarded-For `$proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto `$scheme;
            
            # 超时设置
            proxy_connect_timeout 30s;
            proxy_send_timeout 30s;
            proxy_read_timeout 30s;
            
            # 缓冲设置
            proxy_buffering on;
            proxy_buffer_size 4k;
            proxy_buffers 8 4k;
            
            # CORS支持
            add_header Access-Control-Allow-Origin *;
            add_header Access-Control-Allow-Methods 'GET, POST, PUT, DELETE, OPTIONS';
            add_header Access-Control-Allow-Headers 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization';
            
            if (`$request_method = 'OPTIONS') {
                return 204;
            }
        }
        
        # 静态资源缓存
        location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)`$ {
            expires 1y;
            add_header Cache-Control "public, immutable";
        }
        
        # HTML文件缓存
        location ~* \.html`$ {
            expires 1h;
            add_header Cache-Control "public";
        }
    }
}
"@

    $configPath = "$NginxPath\conf\nginx.conf"
    
    # 备份原配置
    if (Test-Path $configPath) {
        $backupPath = "$configPath.backup.$(Get-Date -Format 'yyyyMMdd_HHmmss')"
        Copy-Item $configPath $backupPath
        Write-Host "原配置已备份到：$backupPath" -ForegroundColor Blue
    }
    
    # 写入新配置
    $nginxConfig | Out-File -FilePath $configPath -Encoding UTF8
    Write-Success "Nginx配置文件已生成"
    Write-Host ""

    # 步骤4：测试配置
    Write-Step "4/6" "测试Nginx配置"
    Set-Location $NginxPath
    $testResult = & .\nginx.exe -t 2>&1
    if ($LASTEXITCODE -ne 0) {
        Write-Error-Custom "Nginx配置测试失败"
        Write-Host $testResult -ForegroundColor Red
        Set-Location $currentPath
        Read-Host "按任意键退出"
        exit 1
    }
    Write-Success "Nginx配置测试通过"
    Write-Host ""

    # 步骤5：启动Nginx
    Write-Step "5/6" "启动Nginx服务"
    
    # 检查是否已有Nginx进程
    $nginxProcess = Get-Process -Name "nginx" -ErrorAction SilentlyContinue
    if ($nginxProcess) {
        Write-Host "检测到Nginx正在运行，重新加载配置..." -ForegroundColor Blue
        & .\nginx.exe -s reload
        if ($LASTEXITCODE -ne 0) {
            Write-Warning-Custom "重新加载失败，尝试重启Nginx"
            & .\nginx.exe -s stop
            Start-Sleep -Seconds 2
            & .\nginx.exe
        }
    } else {
        Write-Host "启动Nginx服务..." -ForegroundColor Blue
        & .\nginx.exe
        if ($LASTEXITCODE -ne 0) {
            Write-Error-Custom "Nginx启动失败"
            Set-Location $currentPath
            Read-Host "按任意键退出"
            exit 1
        }
    }
    
    # 等待服务启动
    Start-Sleep -Seconds 2
    
    # 检查服务状态
    $nginxProcess = Get-Process -Name "nginx" -ErrorAction SilentlyContinue
    if (-not $nginxProcess) {
        Write-Error-Custom "Nginx服务启动失败"
        Set-Location $currentPath
        Read-Host "按任意键退出"
        exit 1
    }
    
    Write-Success "Nginx服务启动成功"
    Set-Location $currentPath
    Write-Host ""

    # 步骤6：验证部署
    Write-Step "6/6" "验证部署结果"
    $testUrl = "http://${DomainName}:${Port}${AccessPath}"
    
    Write-Host "正在测试访问..." -ForegroundColor Blue
    try {
        $response = Invoke-WebRequest -Uri $testUrl -TimeoutSec 10 -ErrorAction Stop
        if ($response.StatusCode -eq 200) {
            Write-Success "网站访问测试通过"
        } else {
            Write-Warning-Custom "网站返回状态码：$($response.StatusCode)"
        }
    } catch {
        Write-Warning-Custom "网站访问测试失败，但这可能是正常的（可能需要登录）"
        Write-Host "错误信息：$($_.Exception.Message)" -ForegroundColor Gray
    }
    
    Write-Host ""
    Write-Host "========================================" -ForegroundColor Cyan
    Write-Host "🎉 部署完成！" -ForegroundColor Green
    Write-Host ""
    Write-Host "📍 访问地址：" -ForegroundColor Yellow
    Write-Host "   $testUrl" -ForegroundColor Green
    Write-Host ""
    Write-Host "📁 重要路径：" -ForegroundColor Yellow
    Write-Host "   网站文件：$distPath" -ForegroundColor White
    Write-Host "   Nginx配置：$configPath" -ForegroundColor White
    Write-Host "   Nginx日志：$NginxPath\logs\" -ForegroundColor White
    Write-Host ""
    Write-Host "🔧 常用命令：" -ForegroundColor Yellow
    Write-Host "   停止服务：cd $NginxPath && nginx -s stop" -ForegroundColor White
    Write-Host "   重新加载：cd $NginxPath && nginx -s reload" -ForegroundColor White
    Write-Host "   查看日志：type $NginxPath\logs\error.log" -ForegroundColor White
    Write-Host ""
    Write-Host "========================================" -ForegroundColor Cyan
    Write-Host ""
    
    # 询问是否打开浏览器
    $openBrowser = Read-Host "是否打开浏览器访问网站？(Y/N)"
    if ($openBrowser -eq "Y" -or $openBrowser -eq "y") {
        Start-Process $testUrl
    }
    
    Write-Success "部署脚本执行完成！"

} catch {
    Write-Error-Custom "部署过程中发生错误：$($_.Exception.Message)"
    Write-Host $_.ScriptStackTrace -ForegroundColor Red
} finally {
    Write-Host ""
    Read-Host "按任意键退出"
}